<?php

namespace app\common\service\order\pipeline\coupon;

use app\model\CouponOrder;
use PhpOffice\PhpSpreadsheet\Calculation\DateTimeExcel\Current;
use think\Exception;
use app\model\CouponProductChannel;

/**
 *  验证 参数
 */
class AccountValidate
{
    public static function handle(CouponOrder $couponOrder, $next)
    {

        if (!isProd()){
            return $next($couponOrder);
        }

        $params = $couponOrder->params;

        //校验是否有充值规则
        $product_channel_id = $params['product_channel_id']??'';

        //充值账号
        $account = $params['account']??'';

        /**
         *  @var  CouponProductChannel $couponProductChannel
         */
        try {
            //方案一：前端把规则回传回来，这样可以避免再次查询数据库
            //方案二.自己再查一遍，暂时采用方案二
            $couponProductChannel = CouponProductChannel::query()->where('id', $product_channel_id)
                ->availableSale()
                ->field('id, supplier_id, origin_id, extend')
                ->find();
            if ($couponProductChannel) {
                $template = (new CouponProductChannel())->getTemplate($couponProductChannel->extend);
                $regData = $template['regData'] ?? [];

                //正则判断是否符合规则
                $regLength = count($regData);
                if ($regLength == 0) {
                   return $next($couponOrder);
                }
                if ($regLength == 1) {
                   if (strtoupper(current($regData)) == 'QQ') {
                       if (!checkQQ($account)) {
                           throw new Exception('QQ号格式有误');
                       }
                   } elseif(strtoupper(current($regData)) == 'PHONE') {
                       if (!checkMobile($account)) {
                           throw new Exception('手机号码格式有误');
                       }
                   }
                } elseif($regLength > 1) {
                    if (!checkQQ($account) && !checkMobile($account)) {
                        throw new Exception('充值格式有误');
                    }
                }
            }
        } catch(\Exception $e) {
            throw new Exception($e->getMessage());
        }

        $next($couponOrder);
    }

}